import React, { useState } from 'react';
import { StockOutlined } from '@ant-design/icons';
import ReactECharts from 'echarts-for-react';
import * as echarts from 'echarts';
import { Col, Row, DatePicker } from 'antd';
import { useRequest } from 'ahooks';
import { getFetch } from '@/utils/doFetch';
import moment from 'moment';


let col = { xs: 24, sm: 12, md: 8, lg: 6, xl: 6, xxl: 6 };
let dip = {
  0: {
    title: '空闲',
    color: '#40D851',
  },
  1: {
    title: '充电中',
    color: 'lightblue',
  },
  2: {
    title: '未充占用',
    color: '#BC12ED',
  },
  3: {
    title: '充满占用',
    color: '#0103FD',
  },
  4: {
    title: '端口故障',
    color: '#E40C00',
  },
  5: {
    title: '浮充',
    color: '#06F9E0',
  },
  88: {
    title: '绑定端口',
    color: '#ffac93',
  },
  99: {
    title: '端口禁用',
    color: '#400000',
  },
  170: {
    title: '等待刷卡中',
    color: '#ff4800',
  },
  6: {
    title: '存储器损坏',
    color: '#005BAC',
  },
  7: {
    title: '安全门卡住',
    color: '#d3ac2b',
  },
  8: {
    title: '接触不良或保险丝烧断',
    color: '#009DA2',
  },
  9: {
    title: '继电器粘连',
    color: '#ee45e4',
  },
  10: {
    title: '霍尔芯片损坏',
    color: '#FDF204',
  },
};
const { RangePicker } = DatePicker;

let timeSeg = (startT = "09:00", endT = "14:00", interval = 15) => {
  console.log(endT.format("MM-DD HH:mm"));
  let starTime = startT;
  let endTime = endT;
  let diff = endTime.diff(starTime, "minutes");
  let num = Math.ceil(diff / interval);
  var segs = []
  for (let i = 1; i <= num - 1; i++) {
    let timeFrom = starTime.clone().add((i - 1) * interval, "minutes")
    let timeTo = starTime.clone().add(i * interval, "minutes");
    let minutes = timeFrom.minutes();
    let hour = timeFrom.hour()
    segs.push({
      timeFrom: timeFrom.format("MM-DD HH:mm"),
      timeTo: timeTo.format("MM-DD HH:mm"),
      timeTos: timeTo,
      title: (hour < 12 ? "上午" : "下午") + hour + '点'
    });
  }
  return segs
}, cur = 200

function Voltage() {
  const [params, setparams] = useState({
    start_time: moment().startOf('day'),
    end_time: moment(),
  });

  let { data, loading } = useRequest(() => {
    return getFetch({ url: "/vehicle-api/charge/devices" })
  })




  let option = (key) => {
    return {
      tooltip: {
        trigger: 'axis',
      },
      grid: {
        left: '0px',
        right: '0px',
        bottom: '0px',
        top: '28px',
        containLabel: true,
      },
      toolbox: {
        feature: {
          dataView: {
            show: false,
            readOnly: false,
          },
          restore: {
            show: false,
          },
          saveAsImage: {
            show: false,
          },
        },
      },
      xAxis: {
        type: 'category',
        axisTick: {
          alignWithLabel: false,
        },
        axisLabel: {
          color: '#FFF',
        },
        align: 'center',
        data: timeSeg(params.start_time, params.end_time, 15).map(it => it.timeTo)
      },
      yAxis: [
        {
          type: 'value',
          name: '功率(w)',
          position: 'left',
          axisLabel: {
            formatter: '{value}',
            color: '#FFF',
          },
          splitLine: {
            show: false,
          },
        },
        {
          type: 'value',
          name: '电压(v)',
          position: 'right',
          axisLabel: {
            formatter: '{value}',
            color: '#FFF',
          },
          splitLine: {
            show: false,
          },
        },
      ],
      series: [
        {
          name: '功率(w)',
          type: 'line',
          data: timeSeg(params.start_time, params.end_time, 15).map((it, i) => {
            if (key == 1 && moment(it.timeTos).valueOf() < moment().valueOf()) {
              return 200 + parseInt(Math.random() * 10)
            } else if (key == 3) {
              let step = parseInt(Math.random() * 10);
              if (i < 18) {
                return 200 + parseInt(Math.random() * 10)
              } else {
                return cur < 0 ? 0 : cur -= step;
              }
            } else {
              return 0
            }
          }),
          lineStyle: {
            color: '#ff4800',
            width: 1,
          },
          symbol: "none"
        },
        {
          name: '电压(v)',
          type: 'line',
          yAxisIndex: 1,
          data: timeSeg(params.start_time, params.end_time, 15).map(it => {
            if (moment(it.timeTos).valueOf() < moment().valueOf()) {
              return 220 + parseInt(Math.random() * 10)
            } else {
              return 0
            }
          }),
          lineStyle: {
            color: 'lightblue',
            width: 1,
          },
          symbol: "none"
        },
      ],
    };
  }

  function disabledDate(current) {
    // Can not select days before today and today
    return current && current > moment().endOf('day');
  }
  return (
    <div>
      <p className="title" style={{ marginBottom: 12, display: 'flex', justifyContent: 'space-between', padding: 0 }}>
        <span>
          <StockOutlined style={{ paddingRight: 6 }} />
          实时电压曲线
        </span>
        <RangePicker
          size="small"
          disabledDate={disabledDate}
          style={{ height: 26 }}
          showTime={{
            defaultValue: [moment('00:00', 'HH:mm'), moment('11:59', 'HH:mm')],
          }}
          value={[params.start_time ?? moment(), params.end_time ?? moment()]}
          onChange={(val) => {
            setparams({
              start_time: val[0],
              end_time: val[1],
            });
          }}
        />
      </p>
      <Row style={{ width: 'calc(100% + 12px)' }} gutter={12}>
        {
          data?.rows &&
          data.rows.map((it, i) => {

            let portList = it.portList ? JSON.parse(it.portList) : [];

            return portList.map((item, index) => {
              return <Col
                {...col}
                key={i + index}
                style={{
                  height: '24vh',
                  marginBottom: 12,
                }}
              >
                <div
                  style={{
                    backgroundColor: 'rgba(0,0,0,0.2)',
                    border: '1px solid rgba(82, 136, 198, 0.4)',
                    height: '100%',
                    width: '100%',
                    color: '#fff',
                    display: 'flex',
                    flexDirection: "column",
                    overflow: "hidden"
                  }}
                >
                  <p className="title" style={{ margin: 0, padding: 0, height: 36, lineHeight: "36px", textIndent: 8, display: "flex", justifyContent: "space-between" }}>
                    <span>{it.code} {dip[item].title}</span>
                    <b style={{ paddingRight: 10 }}>{index + 1}口</b>
                  </p>
                  <div style={{ flex: 1, padding: 8 }}>
                    <ReactECharts
                      option={option(item)}
                      style={{ height: '100%', width: '100%' }}
                    />
                  </div>

                </div>
              </Col>
            });
          })}
      </Row>
    </div>
  );
}

export default Voltage;
